package com.alpha.components;

import com.alpha.module.sys.entity.SysConfig;
import com.alpha.module.sys.service.SysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class StartRunInit implements CommandLineRunner {

    private static final Logger LOGGER = LoggerFactory.getLogger(StartRunInit.class);

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private Environment environment;

    @Override
    public void run(String... args) throws Exception {
        initSystemConfig();
    }

    private void initSystemConfig() {
        LOGGER.info("开始初始化启动服务");
        LOGGER.info("服务名称：{}", environment.getProperty("spring.application.name"));
        LOGGER.info("服务端口：{}", environment.getProperty("server.port"));
        LOGGER.info("服务环境：{}", environment.getProperty("spring.profiles.active"));
        LOGGER.info("数据源地址：{}", environment.getProperty("spring.datasource.url"));
        LOGGER.info("redis主机地址：{}", environment.getProperty("spring.redis.host"));
        LOGGER.info("redis端口：{}", environment.getProperty("spring.redis.port"));
        initSysConfig();
    }

    private void initSysConfig() {
        LOGGER.info("开始初始化系统动态配置");
        List<SysConfig> sysConfigs = sysConfigService.cacheAllConfig();
        for (SysConfig sysConfig : sysConfigs) {
            LOGGER.info("开始写入：" + sysConfig.getNid() + "---" + sysConfig.getValue());
            GlobalConfigMap.addConfig(sysConfig.getNid(), sysConfig.getValue());
        }
        LOGGER.info("初始化系统动态配置结束");
    }
}
